using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.Presents
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="Present"/> instances.
    /// </summary>
    public class PresentCommandHandler :
        ICommandHandler<EnterPresent>,
        ICommandHandler<ChangePresent>,
        ICommandHandler<DeletePresent>
    {
        private readonly IRepository _repository;

        public PresentCommandHandler(IRepository repository)
        {
            _repository = repository;
        }

        public void Handle(EnterPresent command)
        {
            Present present = new Present(command.PresentId, command.PresentTemplateId, command.PersonId, command.SponsorId, command.PresentData, command.Comment);
            SavePresent(present);
        }

        public void Handle(ChangePresent command)
        {
            Present present = _repository.GetById<Present>(command.PresentId, command.Version);
            present.Change(command.PresentTemplateId, command.PersonId, command.SponsorId, command.PresentData, command.Comment);
            SavePresent(present);
        }

        public void Handle(DeletePresent command)
        {
            Present present = _repository.GetById<Present>(command.PresentId, command.Version);
            present.Delete();
            SavePresent(present);
        }

        private void SavePresent(Present present)
        {
            _repository.Save(present, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}